package com.winit.openapi.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.oms.spi.isp.PrintInvoiceService;
import com.winit.oms.spi.isp.command.PrintInvoiceCommand;
import com.winit.oms.spi.isp.vo.ISPInvoice;
import com.winit.oms.spi.vo.Invoice;
import com.winit.oms.spi.vo.InvoiceInfo;
import com.winit.oms.spi.vo.PrintInvoiceResult;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.DateUtil;
import com.winit.openapi.util.PDFBox4MergePDF;
import com.winit.openapi.util.ValidateUtil;

/**
 * 打印
 * 
 * @version Revision History
 * 
 * <pre>
 * Author     Version       Date        Changes
 * long.yue    1.0           2015年1月8日     Created
 * 
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/winitInvoice")
public class WinitInvoiceController extends BaseController {

    private Logger            logger = LoggerFactory.getLogger(WinitInvoiceController.class);
    
    @Resource
    private PrintInvoiceService printInvoiceService;

    /**
     * OpenAPI 打印发票，获取到文件地址后用64base编码
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/query")
    public String query(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        ValidateUtil.validNotNull(json, "orderNo");
       // ValidateUtil.validMaxLength(json, "orderNo", 60);
        
        String os = System.getProperty("os.name");
        String prePath = os.toLowerCase().startsWith("win") ? ApiConstant.PATH_MERGE_PDF_WIN : ApiConstant.PATH_MERGE_PDF_LINUX;
        String path = prePath + DateUtil.getCurrentDate() + ".pdf";

        PrintInvoiceCommand command = new PrintInvoiceCommand();
        this.buildCommand(json, command);
        List<ISPInvoice> labels = command.getiSPInvoice();
        
        // result
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<String> files = new ArrayList<String>();
        if (labels.size() == 1) {
            InvoiceInfo invoiceInfo= printInvoiceService.printInvoice(command);
            List<String> invoicePaths = new ArrayList<String>();
            for (Invoice invoice : invoiceInfo.getInvoiceList()) {
            	invoicePaths.add(invoice.getFilePath());
             }
            
            PDFBox4MergePDF tool = new PDFBox4MergePDF();
            try {
	            tool.merge(invoicePaths, path,invoiceInfo.getPrintQty());
	            files.add(tool.file2Base64(path));
            } catch (Exception e) {
                logger.error("WinitInvoiceController->query :error:{}", e);
            } finally {
                // 删除临时文件
                tool.delFile(path);
            }
        } else if (labels.size() > 1) {
            // 批量打印面单
        	PrintInvoiceResult invoiceInfo= printInvoiceService.multilPrintInvoice(command);
            List<String> invoicePaths = invoiceInfo.getInvoicePath();
            PDFBox4MergePDF tool = new PDFBox4MergePDF();
            try {
                tool.merge(invoicePaths, path,3);
                files.add(tool.file2Base64(path));
            } catch (Exception e) {
                logger.error("WinitInvoiceController->query :error:{}", e);
            } finally {
                // 删除临时文件
                tool.delFile(path);
            }
            dataMap.put("successCount", invoiceInfo.getSuccess());
            dataMap.put("failedCount", invoiceInfo.getFailed());
        }
        dataMap.put("files", files);
        responseMsg.setData(dataMap);
        return SUCCESS;
    }

    /**
     * 构造打印面单对象
     * 
     * @param json
     * @param command
     */
    private void buildCommand(JSONObject json, PrintInvoiceCommand command) {
        if (StringUtils.isNotBlank(json.getString("orderNo"))) {
            String[] arr = json.getString("orderNo").split(",");
            List<ISPInvoice> invoices = new ArrayList<ISPInvoice>();
            for (int i = 0; i < arr.length; i++) {
                if(StringUtils.isNotBlank(arr[i])){
                    ISPInvoice ispInvoice = new ISPInvoice();
                    ispInvoice.setOrderNO(arr[i]);
                    invoices.add(ispInvoice);
                }
            }
            command.setiSPInvoice(invoices);
        }
    }
}
